package mcsm.DataBaseIntegration;

import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import mcsm.DataBaseInterface.AddOperation;
import mcsm.Model.Goods;
import mcsm.Model.ReturnUnit;
import mcsm.Model.VIP;

public class AddReturnUnitConnect implements AddOperation {

	private ReturnUnit returnUnit;
	
	private int returnUnitNum;
	
	public AddReturnUnitConnect(ReturnUnit returnUnit) {
		this.returnUnit = returnUnit;
	}

	@Override
	public Boolean connect(Statement statement) {
		int i = 0;
		try {
			i = statement.executeUpdate(add());
			statement.executeUpdate("update number set returnUnit = " + returnUnitNum);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return (i != 0);
	}

	@Override
	public String add() {
		DataBaseConnect database = DataBaseConnect.getDatabase();
		returnUnitNum = database.getReturnUnitNumber() + 1;
		String id = database.getNewReturnUnitID();
		String cashierID = returnUnit.getCashierID();
		ArrayList<Goods> goods = returnUnit.getReturnGoodsList();
		String goodsIDs = "";
		String goodsNum = "";
		for(int j = 0; j < goods.size(); j++) {
			database.increaseGoodsNum(goods.get(j).getGoodsID(), goods.get(j).getQuantity());
			if(goodsIDs.equals("")) {
				goodsIDs = goodsIDs + goods.get(j).getGoodsID();
				goodsNum = goodsNum + goods.get(j).getQuantity();
			}else {
				goodsIDs = goodsIDs + ", " + goods.get(j).getGoodsID(); 
				goodsNum = goodsNum + ", " + goods.get(j).getQuantity();
			}
		}
	
		
		double refond = returnUnit.getRefond();
		double ticketReturn = returnUnit.getTicketReturn();
		VIP vip = returnUnit.getVIP();
		String vipID = "";
		if(vip != null) {
			vipID = vip.getID();
		}
		String date = returnUnit.getReturnData();
		
		
		String sql = "insert into returnunit values ('" + id + "', '" + cashierID + "', '" + goodsIDs + "', " + refond + ", " + ticketReturn + ", '" + vipID + "', '" + date + "', '" + goodsNum + "')";
		
		return sql;
	}

}
